package com.ruan.service;

import com.ruan.dao.AdminMapper;
import com.ruan.entity.Admin;
import com.ruan.entity.Result;
import com.ruan.utils.Auth0JwtUtils;
import com.ruan.utils.LongAuth0JwtUtils;
import com.ruan.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:AdminService
 * @Author:阮昇
 * @Description:
 * @Datetime: 2023/6/30 14:24
 **/
@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisUtil redisUtil;

    public Result login(Admin admin1) {
        Admin admin = adminMapper.getAdminByName(admin1.getAdminName());
        if(admin == null){

            return new Result(100,"用户名错误");

        }else {

            if(!admin1.getAdminPwd().equals(admin.getAdminPwd())){

                return new Result(100,"密码错误");

            }

            Map<String,Object> map = new HashMap<>();

            map.put("userId",admin.getId());

            String token = Auth0JwtUtils.sign(map);

            String refreshToken = LongAuth0JwtUtils.sign(map);

            redisUtil.set("adminId", String.valueOf(admin.getId()));

            System.err.println(redisUtil.get("adminId"));

            redisUtil.set("refreshToken",refreshToken);

            admin.setAdminPwd(null);

            return new Result(200,"登陆成功",admin,token,refreshToken);

        }
    }

    public Result addAdmin(Admin admin1) {
        Admin admin = adminMapper.getAdminByName(admin1.getAdminName());
        if(admin != null){
            return new Result(100,"该管理员账户已存在");
        }
        int row = adminMapper.addAdmin(admin1);
        if(row != 1){
            return new Result(100,"添加失败");
        }else {
            return new Result(200,"添加成功");
        }
    }
}
